package edu.uwo.se2.group3mapapp;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.util.Log;
import android.util.Xml;

public class FriendLocationParser extends XmlParser {
	
	public Response<FriendLocation> parse(InputStream in) throws XmlPullParserException, IOException {
		try {
			XmlPullParser parser = Xml.newPullParser();
			parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
			parser.setInput(in, null);
			parser.nextTag();
			return readFeed(parser);
		} finally {
			if (in != null)
				in.close();
		}
	}

	private Response<FriendLocation> readFeed(XmlPullParser parser) throws XmlPullParserException, IOException {
		Log.d("XML", "Starting to read feed");
		Response<FriendLocation> response = new Response<FriendLocation>();
		parser.require(XmlPullParser.START_TAG, ns, "response");
		while (parser.next() != XmlPullParser.END_TAG) {
			if (parser.getEventType() != XmlPullParser.START_TAG) {
				continue;
			}
			String name = parser.getName();
			//		        Log.d("XML", "Count: " + parser.getAttributeCount());

			// Starts by looking for the entry tag
			if (name.equals("status")) {
				Status s = new Status();
				s.isSuccessful = Boolean.parseBoolean(parser.getAttributeValue(ns, "isSuccessful"));
				s.content = readText(parser);
				response.status = s;
			} else if (name.equals("friends")) {
				parseUsers(response, parser);
			} else {
				skip (parser);
			}
		}  
		return response;

	}

	private void parseUsers(Response<FriendLocation> response, XmlPullParser parser) throws XmlPullParserException, IOException {
		// TODO Auto-generated method stub
		parser.require(XmlPullParser.START_TAG, ns, "friends");

		while (parser.next() != XmlPullParser.END_TAG) {
			if (parser.getEventType() != XmlPullParser.START_TAG) {
				continue;
			}

			String name = parser.getName();
			if (name.equals("friend")) {
				FriendLocation f = new FriendLocation();
				f.fid = Integer.parseInt(parser.getAttributeValue(ns, "friendId"));
				f.name = parser.getAttributeValue(ns, "friendUsername");
				f.lat = Double.parseDouble(parser.getAttributeValue(ns, "latitude"));
				f.lng = Double.parseDouble(parser.getAttributeValue(ns, "longitude"));
				response.list.add(parseUser(f, parser));
			} else {
				skip (parser);
			}
		}
	}

	private FriendLocation parseUser(FriendLocation u, XmlPullParser parser) throws XmlPullParserException, IOException {
		// TODO Auto-generated method stub
		parser.require(XmlPullParser.START_TAG, ns, "friend");
		String x = readText(parser);
		parser.require(XmlPullParser.END_TAG, ns, "friend");
		return u;
	}
}